//
//  ZCRegsitVC.m
//  ZCJZ
//
//  Created by sujeking on 2019/3/26.
//  Copyright © 2019年 jeking. All rights reserved.
//

#import "ZCRegsitVC.h"
#import "ZCAddNewAddressInputCell.h"
#import "ZCRegsitVCSendCodeCell.h"
#import "ZCRegsitVCInputCell.h"

#import "ZCLoginViewModel.h"
#import "ZCRegistProticoyView.h"
#import "ZCWebVC.h"
#import "UIImage+Extension.h"
#import <BlocksKit+UIKit.h>


@interface ZCRegsitVC ()<ZCAddNewAddressInputCellDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIButton *doneBtn;
@property (nonatomic, copy) NSArray *staticArr;
@property (nonatomic, strong) NSMutableDictionary *mdict;

@property (nonatomic, copy) NSString *checkpwd;

@end

@implementation ZCRegsitVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupUI];
}

- (void)setupUI {
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.view.backgroundColor = [UIColor whiteColor];
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCAddNewAddressInputCell" bundle:nil]
         forCellReuseIdentifier:@"ZCAddNewAddressInputCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"ZCRegsitVCSendCodeCell" bundle:nil]
         forCellReuseIdentifier:@"ZCRegsitVCSendCodeCell"];

    [self.tableView registerNib:[UINib nibWithNibName:@"ZCRegsitVCInputCell" bundle:nil]
         forCellReuseIdentifier:@"ZCRegsitVCInputCell"];

    self.doneBtn.layer.cornerRadius = 5.0f;
    self.doneBtn.layer.masksToBounds = YES;
    [self.doneBtn setBackgroundImage:[UIImage imageFromColor:[generalToolBox getColorWithHexadecimalColorStr:@"0xF9150F"]] forState:UIControlStateNormal];
    [self.doneBtn setBackgroundImage:[UIImage imageFromColor:[generalToolBox getColorWithHexadecimalColorStr:@"0x999999"]] forState:UIControlStateDisabled];
    self.doneBtn.enabled = NO;
    
    [self.mdict setValue:self.wxcode forKey:@"wxcode"];
    [self.mdict setValue:@(3) forKey:@"type"];
    [self.mdict setValue:@(0) forKey:@"referrer_uid"];
    
    [self.doneBtn bk_addEventHandler:^(id sender) {
        [self.view endEditing:YES];

        NSString *username = [self.mdict valueForKey:@"username"];
        NSString *pwd = [self.mdict valueForKey:@"pwd"];
        NSString *realname = [self.mdict valueForKey:@"realname"];
        NSString *idcard = [self.mdict valueForKey:@"idcard"];
        NSString *code =  [self.mdict valueForKey:@"code"];
        NSString *phone = [self.mdict valueForKey:@"phone"];
        NSString *tui_code = [self.mdict valueForKey:@"tui_code"];
        
        
        if (username.length == 0 ) {
            [self.view makeToast:@"请输入账号" duration:2.0 position:CSToastPositionCenter];
            return;
        }
        if (pwd.length == 0 ) {
            [self.view makeToast:@"请输入密码" duration:2.0 position:CSToastPositionCenter];
            return;
        }
        if (realname.length == 0 ) {
            [self.view makeToast:@"请输入真实姓名" duration:2.0 position:CSToastPositionCenter];
            return;
        }
        if (idcard.length == 0 ) {
            [self.view makeToast:@"请输入身份证号" duration:2.0 position:CSToastPositionCenter];
            return;
        }
        if (phone.length == 0 ) {
            [self.view makeToast:@"请输入手机号" duration:2.0 position:CSToastPositionCenter];
            return;
        }
        if (code.length == 0 ) {
            [self.view makeToast:@"请输入验证码" duration:2.0 position:CSToastPositionCenter];
            return;
        }
     
        
        if (![self.checkpwd isEqualToString:pwd]) {
            [self.view makeToast:@"两次密码不一致,请检查" duration:2.0 position:CSToastPositionCenter];
            return;
        }
        
        if (tui_code.length == 0) {
            [self.mdict setValue:nil forKey:@"tui_code"];
        }
        
        
        [self netCommitInfo2Server4Regist];
    } forControlEvents:UIControlEventTouchUpInside];
    
    {
        UIView *headerView = [[UIView alloc] initWithFrame:(CGRect){0,0,[UIScreen mainScreen].bounds.size.width,80}];
        UINib *nib = [UINib nibWithNibName:@"ZCRegistProticoyView" bundle:nil];
        ZCRegistProticoyView *view = [nib instantiateWithOwner:self options:nil].firstObject;
        [view setCheckBtnClickCallback:^(BOOL flag) {
            self.doneBtn.enabled = flag;
        }];
        
        [view setFileBtnClickCallback:^(NSInteger idx) {
            ZCWebVC *vc = [[ZCWebVC alloc] init];
            NSString *path = [[NSBundle mainBundle] pathForResource:@"setting" ofType:@"bundle"];
            NSBundle *bundle = [NSBundle bundleWithPath:path];
            switch (idx) {
                case 0:
                {
                    NSString *h5path = @"http://shaoyue.ec-cloudtech.com/#/protocol/register";
                    vc.remotePath = h5path;
                    vc.navTitle = @"用户协议";
                }
                    break;
                case 1:
                {
                    NSString *h5path = @"http://shaoyue.ec-cloudtech.com/#/protocol/protocol1";
                    vc.remotePath = h5path;
                    vc.navTitle = @"注册协议";
                }
                    break;
                case 2:
                {
                    NSString *path = [[NSBundle mainBundle] pathForResource:@"idauth" ofType:@"bundle"];
                    NSBundle *bundle = [NSBundle bundleWithPath:path];
                    NSString *h5path = [bundle pathForResource:@"hetong" ofType:@"pdf"];
                    vc.remotePath = h5path;
                    vc.navTitle = @"营销推广服务合同";
                }
                    break;
                    
                default:
                    break;
            }
            [self.navigationController pushViewController:vc animated:YES];
        }];
        view.frame = headerView.bounds;
        [headerView addSubview:view];
        self.tableView.tableFooterView = headerView;
    }
}

// MARK: - UITableViewDelegate,UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.staticArr.count;
    } else {
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSInteger row = indexPath.row;
    NSInteger section = indexPath.section;
    __weak typeof(self) weakSelf = self;
    if (section == 0) {
        
        ZCAddNewAddressInputCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCAddNewAddressInputCell"
                                                                         forIndexPath:indexPath];
        cell.delegate = self;
        cell.keystr = self.staticArr[row];
        cell.type = ZCAddNewAddressInputCellType_Input;
        cell.indexPath = indexPath;
        cell.secureTextEntry = NO;
        switch (row) {
            case 0:
            {
                cell.placeholdstr = @"请输入真实姓名（如账号已存在，请加数字）";
            }
                break;
            case 1:
            {
                cell.placeholdstr = @"请输入密码(8~20位数字或字母)";
                cell.secureTextEntry = YES;
            }
                break;
            case 2:
            {
                cell.placeholdstr = @"请再次输入密码";
                cell.secureTextEntry = YES;
            }
                break;
//            case 3:
//            {
//                cell.placeholdstr = @"请输入真实姓名";
//            }
//                break;
//            case 4:
//            {
//                cell.placeholdstr = @"请输入身份证号";
//            }
//                break;
            case 3:
            {
                cell.placeholdstr = @"请输入推荐码";
            }
                break;
            default:
                break;
        }
        return cell;
    } else {
        if (row == 0) {
            ZCRegsitVCSendCodeCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCRegsitVCSendCodeCell"
                                                                           forIndexPath:indexPath];
            [cell setBtnClickCallback:^(NSString *txt) {
                if (txt == nil || txt.length == 0) {
                    [weakSelf.view makeToast:@"请输入手机号" duration:2.0 position:CSToastPositionCenter];
                } else {
                    [weakSelf.mdict setValue:txt forKey:@"phone"];
                    [weakSelf netSendVirfiyCodeWithPhoneNum:txt];
                }
            }];
            
            [cell setEndEditClickCallback:^(NSString *txt) {
                [weakSelf.mdict setValue:txt forKey:@"phone"];
            }];
            return cell;
        } else {
            ZCRegsitVCInputCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ZCRegsitVCInputCell"
                                                                             forIndexPath:indexPath];
            cell.placeholder = @"请输入验证码";
            [cell setEndInputCallback:^(NSString *txt) {
                [weakSelf.mdict setValue:txt forKey:@"code"];
            }];
            return cell;
        }
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return 110.0f;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 45.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.001f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.01;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
}

// MARK: - ZCAddNewAddressInputCellDelegate

- (void)addNewAddressInputCellInputAction:(NSIndexPath *)indexPath content:(NSString *)content {
    NSInteger row = indexPath.row;
    switch (row) {
        case 0:
        {
            [self.mdict setValue:content forKey:@"username"];
        }
            break;
        case 1:
        {
            [self.mdict setValue:content forKey:@"pwd"];
        }
            break;
        case 2:
        {
            self.checkpwd = content;
        }
            break;
//        case 3:
//        {
//            [self.mdict setValue:content forKey:@"realname"];
//        }
//            break;
//        case 4:
//        {
//            [self.mdict setValue:content forKey:@"idcard"];
//        }
//            break;
        case 3:
        {
            [self.mdict setValue:content forKey:@"tui_code"];
        }
            break;
        default:
            break;
    }
}


// MARK: - NET

- (void)netSendVirfiyCodeWithPhoneNum:(NSString *)phoneNum {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ZCLoginViewModel sendVirfiyCodeWithPhoneNum:phoneNum type:1 complete:^(ZCErrorCode status, NSString *message, id data) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        });
        if (status == kHXSNoError) {
            [weakSelf.view makeToast:@"验证码已发送" duration:2.0 position:CSToastPositionCenter];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"registsendcode" object:nil];
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

- (void)netCommitInfo2Server4Regist {
    __weak typeof(self) weakSelf = self;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [ZCLoginViewModel registAcountServerWithInfo:self.mdict complete:^(ZCErrorCode status, NSString *message, id data) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:weakSelf.view animated:YES];
        });
        if (status == kHXSNoError) {
            [weakSelf.view makeToast:@"操作成功" duration:2.0 position:CSToastPositionCenter];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{        [weakSelf.navigationController popViewControllerAnimated:YES];
            });
        } else {
            [weakSelf.view makeToast:message duration:2.0 position:CSToastPositionCenter];
        }
    }];
}

// MARK: - GET

- (NSArray *)staticArr {
    if (_staticArr == nil) {
        _staticArr = @[ @"账号", @"输入密码", @"确认密码", @"推荐码",];
//        _staticArr = @[ @"账号", @"输入密码", @"确认密码", @"真实姓名", @"身份证号码", @"推荐码",];
    }
    return _staticArr;
}

- (NSMutableDictionary *)mdict {
    if (_mdict == nil) {
        _mdict = [NSMutableDictionary new];
    }
    return _mdict;
}

@end
